package com.cskaoyan.controller;


import com.cskaoyan.bean.Category;
import com.cskaoyan.service.CategoryService;
import com.cskaoyan.vo.BaseRespVo;
import com.cskaoyan.vo.L1VO;
import com.cskaoyan.vo.LevelCategoryVO;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RequiresRoles("超级管理员")
@RequestMapping("admin/category")
@RestController

public class CategoryController {


    @Autowired
    CategoryService categoryService;

    @GetMapping("list")
    public BaseRespVo list() {

        List<LevelCategoryVO> categoryVOList = categoryService.getLeveledList();
        return BaseRespVo.ok(categoryVOList);
    }

    @PostMapping("update")
    public BaseRespVo update(@RequestBody @Valid Category category) {

        if (category.getPid() != null && category.getPid().equals(category.getId())) {
            return BaseRespVo.fail("参数无效");
        }
        if ("L2".equals(category.getLevel())) {
            if (category.getPid() == null ) return BaseRespVo.fail("参数无效");
        }
        int i = categoryService.update(category);

        return BaseRespVo.ok();
    }

    @PostMapping("create")
    public BaseRespVo create(@RequestBody Category category) {

        if (category.getLevel() == null || "".equals(category.getLevel()) ||
                category.getName() == null || "".equals(category.getName())
        )
            return BaseRespVo.fail("参数不能为空", 402);
        if("L2".equals(category.getLevel()) &&
                (category.getPid() == null || category.getPid().equals(0) ))
            return BaseRespVo.fail("必须设置二级目录", 402);

        int i = categoryService.create(category);
        return BaseRespVo.ok();
    }


    @GetMapping("l1")
    public BaseRespVo l1() {
        List<L1VO> list = categoryService.getL1();

        return BaseRespVo.ok(list);
    }

    @PostMapping("delete")
    public BaseRespVo delete(@RequestBody @Valid Category category) {
        int count = categoryService.delete(category);

        return BaseRespVo.ok();
    }

}
